﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.MSSQLDAL;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Anke.SHManage.Web.Areas.CM.Controllers
{
    public class CarBasicInfoController : Controller
    {
        //
        // GET: /CM/CarBasicInfo/

        DbContext db = DBContextFactory.GetDBContext();

        //车辆基本信息页面列表
        public ActionResult CarBasicInfoList()
        {
            E_StatisticsPermisson em = UserOperateContext.Current.getMaxPerForStatistics();
            this.ViewData["em"] = em;
            string selfWorkCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
            this.ViewData["selfWorkCode"] = selfWorkCode;
            string selfCenterID = UserOperateContext.Current.Session_UsrInfo.P_Department.DispatchSubCenterID;
            this.ViewData["selfCenterID"] = selfCenterID;
            string selfStationID = UserOperateContext.Current.Session_UsrInfo.P_Department.DispatchSationID;
            this.ViewData["selfStationID"] = selfStationID;
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1267);//判断登录人有无“新增”油卡加油权限
            if (Insert)
            {
                this.ViewData["RolePermissionInsert"] = "Insert";//登录人有新增油卡加油权限
            }


            return View();
        }

        #region 根据TypeID 取字典表内容，赋值combobox
        public ActionResult getDictionarybyTypeID(string TypeID)
        {
            //string TypeID = Request.Form["TypeID"].ToString();
            var list = new TDictionaryBLL().GetListBy(p => p.TypeID == TypeID && p.IsActive == true, p => p.SN);
            return Json(list);
        }

        #endregion

        #region 根据分站ID在车辆基础表中取出车辆牌号

        public ActionResult getPlateByStationID(string stationCode)
        {
                  
                var info = new C_AmbulanceBLL().getPlateByStationID(stationCode);
              return Json(info);
        }
        #endregion

        #region 根据车辆编码来获取车辆编号
        public ActionResult getCarNumberByID(string ID)
        {

            var info = new C_AmbulanceBLL().getCarNumberByambID(ID);

             return Json(info);

        }
        #endregion

        #region  新增方法  判断当新增页面填写了年检日期和保险日期，将分别插入2条数据进2个子表。
        /// <summary>
        /// 新增保存方法， 判断当新增页面填写了年检日期和保险日期，将分别插入2条数据进2个子表。
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveCarBasicInfo(C_Ambulance info)
        {

            int maxID = new C_AmbulanceBLL().getMaxID(); //取最大ID，如果取到，就最大ID +1，如果没有就"00001"

            if (maxID > 0)
            { info.AmbulanceCode = (maxID + 1).ToString("00000"); }  //aa.ToString("000"); C#将int型数字转换成3位字符串，不足的时候，前面补0
            else { info.AmbulanceCode = "00001"; }

            info.isActive = true;//默认启用
            info.isRejected = false;//默认不报废
            info.AnnualSurveyExpireDate = info.AnnualSurveyExpireDate.ToString().Length > 0 ? info.AnnualSurveyExpireDate : Convert.ToDateTime("2200-01-01");
            info.InsuranceExpireDate = info.InsuranceExpireDate.ToString().Length > 0 ? info.InsuranceExpireDate : Convert.ToDateTime("2200-01-01");


            DateTime asdate = Convert.ToDateTime(info.AnnualSurveyDate);
            string tempASDate = (asdate).ToString("yyyyMMdd"); //将年检日期转换为string指定格式！


            int ambresult = new C_AmbulanceBLL().Add(info);

            int asresult = 0;
            if (info.AnnualSurveyDate.ToString().Length > 0)//当填写了年检日期了，存入年检子表
            {
                C_AnnualSurvey ASinfo = new C_AnnualSurvey(); //年检info  

                ASinfo.ID = info.AmbulanceCode + tempASDate; //车辆编码+年检日期作为子表主键
                ASinfo.AmbulanceCode = info.AmbulanceCode;
                ASinfo.FillTime = DateTime.Now;
                //ASinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                ASinfo.AnnualSurveyDate = info.AnnualSurveyDate;
                ASinfo.AnnualSurveyExpireDate = info.AnnualSurveyExpireDate;
                ASinfo.AnnualSurveyNumber = info.AnnualSurveyNumber;
                ASinfo.AnnualSurveyMoney = info.AnnualSurveyMoney;
                asresult = new C_AnnualSurveyBLL().Add(ASinfo);

            }

            DateTime idate = Convert.ToDateTime(info.InsuranceDate);
            string tempIDate = (asdate).ToString("yyyyMMdd");
            int Iresult = 0;
            if (info.InsuranceDate.ToString().Length > 0) //当填写了保险日期了，存入保险子表
            {
                C_Insurance Iinfo = new C_Insurance();//保险info
                Iinfo.ID = info.AmbulanceCode + tempIDate;
                Iinfo.AmbulanceCode = info.AmbulanceCode;
                Iinfo.FillTime = DateTime.Now;
                // Iinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                Iinfo.InsuranceDate = info.InsuranceDate;
                Iinfo.InsuranceExpireDate = info.InsuranceExpireDate;
                Iinfo.InsuranceNumber = info.InsuranceNumber;
                Iinfo.InsuranceMoney = info.InsuranceMoney;
                Iresult = new C_InsuranceBLL().Add(Iinfo);
            }

            if (ambresult > 0 && asresult >= 0 && Iresult >= 0) //主表存储成功， 2个子表存储成功才会显示成功

                return Json(new { Result = "OK", Message = "车辆信息添加成功;年检记录成功;保险记录成功！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);

            else
                return Json(new { Result = "Error", Message = "车辆信息添加失败！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);


        }
        #endregion

        #region 基础页面的查询
        /// <summary>
        /// 页面基本查询
        /// </summary>
        /// <returns></returns>
        public ActionResult DataLoad()
        {
            string zcenterCode = Request.Form["zcenterCode"].ToString();
            string zstationCode = Request.Form["zstationCode"].ToString();
            string zPlateNumber = Request.Form["zPlateNumber"].ToString();
            string zCarNumber = Request.Form["zCarNumber"].ToString();

            DateTime InsuranceDateStart = Convert.ToDateTime(Request.Form["InsuranceDateStart"]);
            DateTime InsuranceDateEnd = Convert.ToDateTime(Request.Form["InsuranceDateEnd"]);
            DateTime AnnualSurveyDateStart = Convert.ToDateTime(Request.Form["AnnualSurveyDateStart"]);
            DateTime AnnualSurveyDateEnd = Convert.ToDateTime(Request.Form["AnnualSurveyDateEnd"]);

            string isActive = Convert.ToString(Request.Form["isActive"]);
            string isReject = Convert.ToString(Request.Form["isReject"]); //2016-12-27 zch
            string messgeIds = Convert.ToString(Request.Form["messgeIds"]);

            E_StatisticsPermisson em = UserOperateContext.Current.getMaxPerForStatistics();
            string selfWorkCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
            string selfCenterID = UserOperateContext.Current.Session_UsrInfo.P_Department.DispatchSubCenterID;
            string selfStationID = UserOperateContext.Current.Session_UsrInfo.P_Department.DispatchSationID;


             string  sortName = Request.Form["sort"];
             string sortOrder = Request.Form["order"];
             if (sortName == "backup2")
             {
                 sortName = "StationCode";
             }


            //获取页容量
            int rows = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int page = int.Parse(Request.Form["page"]);
            //返回总行数
            int total = 0;

            var list = new C_AmbulanceBLL().getAmbDate(page, rows, sortName, sortOrder, ref total, zcenterCode, zstationCode, zPlateNumber, zCarNumber, InsuranceDateStart, InsuranceDateEnd, AnnualSurveyDateStart, AnnualSurveyDateEnd, isActive, isReject, messgeIds, em, selfWorkCode, selfCenterID, selfStationID);
            return Json(new { total = total, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);



        }
        #endregion

        #region 获取编辑的查询，根据ambulanceCode，（基础表的ID ）
        public ActionResult getEditAmb()
        {
            string ambulanceCode = Request.Form["ambulanceCode"].ToString();

            C_Ambulance info = null;

            new C_AmbulanceBLL().getEditAmb(ambulanceCode, out info);
            return Json(new { Info = info }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 修改基础信息，同时将年检和保险存入2个子表，作为保存记录
        [HttpPost]
        public ActionResult EditAmb(C_Ambulance info)
        {
            string ambulanceCode = Request.Form["zz"].ToString();
            bool IFSaveAS = Convert.ToBoolean(Request.Form["IFSaveAS"]); //当 = true,需要保存时，才存
            bool IFSaveI = Convert.ToBoolean(Request.Form["IFSaveI"]);


            info.AmbulanceCode = ambulanceCode;

            int aresult = -1;
            aresult = new C_AmbulanceBLL().Modify(info, "CenterCode", "StationCode", "PlateNumber", "CarNumber", "Brand", "Model", "Type", "UseFor", "EnableDate", "FrameNumber", "EngineNumber", "Price"
                  , "AnnualSurveyDate", "AnnualSurveyNumber", "SelectASDateIntervalCode", "AnnualSurveyExpireDate", "AnnualSurveyMoney", "InsuranceDate", "InsuranceNumber", "SelectIDateIntervalCode", "InsuranceExpireDate", "InsuranceMoney", "TotalDriverKM", "SelectAlarmKMCode", "SelectAlarmDateIntervalCode", "SelectColorCode"
                  , "Long", "Width", "Height", "Wheelbase", "DriveType", "FrontTread", "BackTread", "SelectTireSizeCode", "Displacement", "Power", "SelectSteeringPositionCode", "TotalKG", "Fuel", "ApprovedPassenger", "isRejected", "Remark", "TankVolume", "DistanceType", "MaintainDate", "MaintainKM", "NextMaintainKM");

            int asresult = 0;
            //判断当IFSaveAS =true 时，就存入年检表
            if (IFSaveAS)
            {
                DateTime asdate = Convert.ToDateTime(info.AnnualSurveyDate);
                string tempASDate = (asdate).ToString("yyyyMMdd"); //将年检日期转换为string指定格式！
                string tempID = ambulanceCode + tempASDate; //车辆编码+年检日期作为子表主键

                if (new C_AmbulanceBLL().ifExistAS(tempID))
                {
                    C_AnnualSurvey ASinfo = new C_AnnualSurvey(); //年检info  

                    ASinfo = new C_AmbulanceBLL().ExistAS(tempID);  //取出了ID为tempID 的

                    ASinfo.AmbulanceCode = ambulanceCode;
                    ASinfo.FillTime = DateTime.Now;
                    //ASinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                    ASinfo.AnnualSurveyDate = info.AnnualSurveyDate;
                    ASinfo.AnnualSurveyExpireDate = info.AnnualSurveyExpireDate;
                    ASinfo.AnnualSurveyNumber = info.AnnualSurveyNumber;
                    ASinfo.AnnualSurveyMoney = info.AnnualSurveyMoney;

                    asresult = new C_AnnualSurveyBLL().Modify(ASinfo, "FillTime", "FillPerson", "AnnualSurveyDate", "AnnualSurveyExpireDate", "AnnualSurveyNumber", "AnnualSurveyMoney");
                }

                else
                {
                    C_AnnualSurvey ASinfo = new C_AnnualSurvey();
                    ASinfo.ID = tempID;
                    ASinfo.AmbulanceCode = ambulanceCode;
                    ASinfo.FillTime = DateTime.Now;
                    //ASinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                    ASinfo.AnnualSurveyDate = info.AnnualSurveyDate;
                    ASinfo.AnnualSurveyExpireDate = info.AnnualSurveyExpireDate;
                    ASinfo.AnnualSurveyNumber = info.AnnualSurveyNumber;
                    ASinfo.AnnualSurveyMoney = info.AnnualSurveyMoney;


                    asresult = new C_AnnualSurveyBLL().Add(ASinfo);
                }

            }
            //保险的判断
            int iresult = 0;
            if (IFSaveI)
            {

                DateTime Idate = Convert.ToDateTime(info.InsuranceDate);
                string tempIDate = (Idate).ToString("yyyyMMdd"); //将年检日期转换为string指定格式！
                string tempID = ambulanceCode + tempIDate; //车辆编码+年检日期作为子表主键

                if (new C_AmbulanceBLL().ifExistI(tempID))
                {
                    C_Insurance Iinfo = new C_Insurance(); //年检info  

                    Iinfo = new C_AmbulanceBLL().ExistI(tempID);  //取出了ID为tempID 的

                    Iinfo.AmbulanceCode = ambulanceCode;
                    Iinfo.FillTime = DateTime.Now;
                    //Iinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                    Iinfo.InsuranceDate = info.InsuranceDate;
                    Iinfo.InsuranceExpireDate = info.InsuranceExpireDate;
                    Iinfo.InsuranceMoney = info.InsuranceMoney;
                    Iinfo.InsuranceNumber = info.InsuranceNumber;

                    iresult = new C_InsuranceBLL().Modify(Iinfo, "FillTime", "FillPerson", "InsuranceDate", "InsuranceExpireDate", "InsuranceMoney", "InsuranceNumber");
                }

                else
                {
                    C_Insurance Iinfo = new C_Insurance(); //年检info  
                    Iinfo.ID = tempID;
                    Iinfo.AmbulanceCode = ambulanceCode;
                    Iinfo.FillTime = DateTime.Now;
                    //Iinfo.FillPerson = UserOperateContext.Current.Session_UsrInfo.Name;
                    Iinfo.InsuranceDate = info.InsuranceDate;
                    Iinfo.InsuranceExpireDate = info.InsuranceExpireDate;
                    Iinfo.InsuranceMoney = info.InsuranceMoney;
                    Iinfo.InsuranceNumber = info.InsuranceNumber;
                    iresult = new C_InsuranceBLL().Add(Iinfo);
                }
            }

          
            if (aresult > 0 && asresult >= 0 && iresult >= 0)
            {
                  return Json(new { Result = "OK", Message = "修改车辆信息成功！"}, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            }
            else
            {
                  return Json(new { Result = "Error", Message = "修改车辆信息失败！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            }

        }

        #endregion


        #region 启用禁用车辆基本信息
        [HttpPost]
        public ActionResult CarDisable()
        {
            string AmbulanceCode = Convert.ToString(Request.Form["AmbulanceCode"]);
            bool disable = Convert.ToBoolean(Request.Form["disable"]);
            C_Ambulance model = new C_Ambulance();
            model.isActive = disable;
            model.AmbulanceCode = AmbulanceCode;
            int res = new C_AmbulanceBLL().Modify(model, "isActive");
            string tInfo = "";
            string finfo = "";
            if (disable)
            {
                tInfo = "设置“<span style='color:darkgreen'>有效</span>”成功！";
                finfo = "设置“<span style='color:darkgreen'>有效</span>”失败！";
            }
            else
            {
                tInfo = "设置“<span style='color:red'>无效</span>”成功！";
                finfo = "设置“<span style='color:red'>无效</span>”失败！";
            }
            if (res > 0)
                 return Json(new { Result = "OK", Message = tInfo}, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
              
            else
                return Json(new { Result = "Error", Message = finfo }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 报废车辆
        [HttpPost]
        public ActionResult CarIFReject()
        {
            string AmbulanceCode = Convert.ToString(Request.Form["AmbulanceCode"]);
            bool ifReject = Convert.ToBoolean(Request.Form["ifReject"]);
            C_Ambulance model = new C_Ambulance();
            model.isRejected = ifReject;
            model.AmbulanceCode = AmbulanceCode;
            model.RejectedDate = DateTime.Now;
            int res = new C_AmbulanceBLL().Modify(model, "isRejected", "RejectedDate");
            string tInfo = "";
            string finfo = "";
            if (ifReject)
            {
                tInfo = "“<span style='color:darkgreen'>报废车辆</span>”成功！";
                finfo = "“<span style='color:darkgreen'>报废车辆</span>”失败！";
            }
            else
            {
                tInfo = "“<span style='color:red'>取消报废</span>”成功！";
                finfo = "“<span style='color:red'>取消报废</span>”失败！";
            }
            if (res > 0)
                return this.JsonResult(Utility.E_JsonResult.OK, tInfo, null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, finfo, null, null);
        }

        #endregion


        ////获取卡号(有效的)判断卡号重复存在的
        //public object GetYXCardCodes()
        //{
        //    List<CardList> list = new List<CardList>();
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append(@"select CardCode from C_OilCardInfo where IsActive=1 ");
        //    DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        //    if (ds.Tables[0].Rows.Count > 0)
        //    {
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            CardList info = new CardList();
        //            info.Name = dr["CardCode"].ToString();
        //            list.Add(info);
        //        }
        //    }
        //    return list;
        //}


        //[HttpPost]
        //public ActionResult GetYXCardCodes()
        //{
        //    C_OilCardInfoBLL bll = new C_OilCardInfoBLL();
        //    var result = new object();
        //    result = bll.GetYXCardCode();
        //    return Json(result);
        //}


        // 获取车号(取有效的)判断卡号是否已经存在     
        [HttpPost]
        public ActionResult getCarNumber()
        {


          var    result = new C_AmbulanceBLL().getCarNumberByambID("-1");


          return Json(result);
        }
    }
}
